package io.gitee.bluemiaomiao.dataanalyzebackend.config;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @Author: TLang @Date: 2020/11/8
 *
 * @description: 判断请求是否有权限，没有则报非法请求异常
 */
@Component
public class UrlAccessDecisionManager implements AccessDecisionManager {
  @Override
  public void decide(
      Authentication authentication, Object o, Collection<ConfigAttribute> collection)
      throws AccessDeniedException, InsufficientAuthenticationException {
    for (ConfigAttribute attribute : collection) {
      // 如果是其他的 url 访问，判断有没有登录，没有登录抛出异常
      if ("ROLE_LOGIN".equals(attribute.getAttribute())) {
        if (authentication instanceof AnonymousAuthenticationToken) {
          throw new AccessDeniedException("非法请求");
        } else {
          return;
        }
      }
      Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
      for (GrantedAuthority authority : authorities) {
        if (authority.getAuthority().equals(attribute.getAttribute())) {
          return;
        }
      }
      throw new AccessDeniedException("非法请求");
    }
  }

  @Override
  public boolean supports(ConfigAttribute configAttribute) {
    return false;
  }

  @Override
  public boolean supports(Class<?> aClass) {
    return false;
  }
}
